package com.rdiot.yx485.ui.web

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.webkit.*
import android.webkit.WebSettings.LOAD_NO_CACHE
import android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
import com.github.lzyzsd.jsbridge.BridgeWebView
import com.github.lzyzsd.jsbridge.OnBridgeCallback
import com.google.gson.Gson
import com.gyf.immersionbar.ktx.immersionBar
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.BuildConfig
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseActivity
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.databinding.ActWebBinding

/**
 *
 * @author mR2hao
 * @date 2022/12/28
 */
class WebActivity : BaseActivity<ActWebBinding>() {
    private lateinit var webUrl: String
    private lateinit var title: String
    override fun getLayoutId() = R.layout.act_web
    private var isError = false

    companion object {
        private const val WEB_URL = "webUrl"
        private const val TITLE = "title"

        fun getNewWebIntent(context: Context, url: String, title: String): Intent {
            val intent = Intent(context, WebActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            intent.putExtra(WEB_URL, url)
            intent.putExtra(TITLE, title)
            return intent
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            statusBarView(binding.v)
            statusBarColor(R.color.white)
            navigationBarColor(R.color.white)
            statusBarDarkFont(true)
        }

        webUrl = intent.getStringExtra(WEB_URL) ?: ""
//        title = intent.getStringExtra(TITLE) ?: ""
//        binding.nb.setTitle(title)
//        binding.nb.setLeftClickListener {
//            if (binding.wv.canGoBack()) {
//                binding.wv.goBack()
//            } else {
//                finish()
//            }
//        }
        initWebView()
    }

    private fun initWebView() {
        val webView: BridgeWebView = binding.wv
        webView.addJavascriptInterface(MainJavascriptInterface(webView.callbacks, webView, this), "WebViewJavascriptBridge")
        webView.setGson(Gson())
        webView.apply {

            webView.webViewClient = object : WebViewClient() {
                override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                    super.onPageStarted(view, url, favicon)
                    binding.wv.visibility = View.GONE
                    binding.bridgeLayoutMainGif.visibility = View.VISIBLE
                }

                //
                override fun onPageFinished(webView: WebView?, s: String?) {
                    super.onPageFinished(webView, s)
                    binding.wv.visibility = View.VISIBLE
                    binding.bridgeLayoutMainGif.visibility = View.GONE
                }
            }






//            webView.webViewClient = object : WebViewClient() {
//                override fun shouldOverrideUrlLoading(
//                    view: WebView?,
//                    request: WebResourceRequest
//                ): Boolean {
//                    view?.loadUrl(request.url.toString())
//                    return true
//                }
//
    //                override fun onPageFinished(webView: WebView?, s: String?) {
//                    super.onPageFinished(webView, s)
//                    //如果有问题，会先执行error，
//                    if (isError) {
//                        binding.wv.visibility = View.GONE
//                        binding.bridgeLayoutMainGif.visibility = View.GONE
//                    } else {
//                        binding.wv.visibility = View.VISIBLE
//                        binding.bridgeLayoutMainGif.visibility = View.GONE
//                    }
//                }
//
//                override fun onReceivedError(
//                    webView: WebView?,
//                    webResourceRequest: WebResourceRequest,
//                    webResourceError: WebResourceError?
//                ) {
//                    super.onReceivedError(webView, webResourceRequest, webResourceError)
//                    if (webResourceRequest.isForMainFrame) {
//                        //加载失败后，需要设置isLoadSuccess为false
//                        isError = true
//                    }
//                }
//            }
            //webView.setDefaultHandler(DefaultHandler())
//            webView.webChromeClient = object : WebChromeClient() {
//                override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
//                    LogUtils.d("consoleMessage:${consoleMessage?.message().toString()}")
//                    return super.onConsoleMessage(consoleMessage)
//                }
//
//                override fun onReceivedTitle(view: WebView?, title: String?) {
//                    super.onReceivedTitle(view, title)
//                }
//            }
            val userAgent = settings.userAgentString

            settings.apply {
                javaScriptEnabled = true
                useWideViewPort = true
                loadWithOverviewMode = false
                userAgentString = "$userAgent yongxulvjian/1.0.0"
                javaScriptCanOpenWindowsAutomatically =
                    true//JavaScript 可以自动打开新窗口，这是通过使用 window.open() 方法实现的
                allowFileAccess = true //当设置为true,就可以 使用file://加载文件
                setSupportMultipleWindows(true)
                allowUniversalAccessFromFileURLs = true//允许跨域
                mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW
                pluginState = WebSettings.PluginState.ON
                domStorageEnabled = true
                cacheMode = LOAD_NO_CACHE
            }

            WebView.setWebContentsDebuggingEnabled(true)

        }
        binding.wv.loadUrl(webUrl)
    }


    /**
     * 设置点击返回按钮，跳转到上一个html页面，而不是退出当前activity
     * @param keyCode
     * @param event
     * @return
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (event.keyCode == KeyEvent.KEYCODE_BACK) {
            if (binding.wv.canGoBack()) {
                //获取webView的浏览记录
                val mWebBackForwardList: WebBackForwardList = binding.wv.copyBackForwardList()
                //这里的判断是为了让页面在有上一个页面的情况下，跳转到上一个html页面，而不是退出当前activity
                if (mWebBackForwardList.currentIndex > 0) {
                    val historyUrl: String =
                        mWebBackForwardList.getItemAtIndex(mWebBackForwardList.currentIndex - 1)
                            .url
                    if (historyUrl != webUrl) {
                        binding.wv.goBack()
                        return true
                    }
                }
            } else {
                return super.onKeyDown(keyCode, event)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onBackPressed() {
        if (binding.wv.canGoBack()) {
            binding.wv.goBack()
        } else {
            super.onBackPressed()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.wv.loadUrl("about:blank")
        binding.wv.destroy()
    }
}

class MainJavascriptInterface : BridgeWebView.BaseJavascriptInterface {
    private var mWebView: BridgeWebView? = null
    private var _context: WebActivity? = null
    constructor(callbacks: Map<String?, OnBridgeCallback?>?, webView: BridgeWebView?, context: WebActivity) : super(
        callbacks
    ) {
        _context = context
        mWebView = webView
    }

    constructor(callbacks: Map<String?, OnBridgeCallback?>?) : super(callbacks)

    override fun send(data: String): String {
        return "it is default response"
    }

    @JavascriptInterface
    fun getCurrentRoomId(data: String, callbackId: String) {
        Log.d(
            "MainJavascriptInterface",
            data + ", callbackId: " + callbackId + " " + Thread.currentThread().name
        )
        mWebView!!.sendResponse("{\"responseData\":\"${LocalData.selFamilyId.value}\"}", callbackId)
    }
    @JavascriptInterface
    fun closeWebView(data: String, callbackId: String) {
        Log.d(
            "MainJavascriptInterface",
            data + ", callbackId: " + callbackId + " " + Thread.currentThread().name
        )
        _context?.finish();
    }
    @JavascriptInterface
    fun getToken(data: String, callbackId: String) {
        Log.d(
            "MainJavascriptInterface",
            data + ", callbackId: " + callbackId + " " + Thread.currentThread().name
        )
        mWebView!!.sendResponse("{\"responseData\":\"${LocalData.loginData?.accessToken}\"}", callbackId)
    }
}